package com.lry.basic.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.Pipe;
import java.nio.charset.Charset;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/9/9
 */
public class Demo4 {
    public static void main(String[] args) throws IOException {
        final Pipe pipe = Pipe.open();
        Pipe.SinkChannel sinkChannel = pipe.sink();//向这里写数据
        //缓冲区
        ByteBuffer buf = ByteBuffer.allocate(100);
        buf.put("hello world".getBytes());
        buf.flip();
        //向管道写数据
        sinkChannel.write(buf);
        buf.clear();

        new Thread(new Runnable() {
            ByteBuffer buf = ByteBuffer.allocate(100);
            @Override
            public void run() {
                //从管道读取数据
                Pipe.SourceChannel sourceChannel = pipe.source();
                while(true){
                    try {
                        if (!(sourceChannel.read(buf)>0)) break;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    buf.flip();
                    CharBuffer cb = Charset.forName("UTF-8").decode(buf);
                    System.out.println(cb.toString());
                    buf.clear();
                }
            }
        }).start();
    }
}
